//
//  GYHUserAccount.swift
//  sinaWeibo_18
//
//  Created by 高勇华 on 15/10/8.
//  Copyright © 2015年 高勇华. All rights reserved.
//

import UIKit

class GYHUserAccount: NSObject ,NSCoding{

    //用于调用access_token，接口获取授权后的access token
    var access_token: String?
    //过期时间
    var expires_date: NSDate?
    //access_token的生命周期，单位是秒数
    var expires_in: NSTimeInterval = 0{
        didSet{
        
        expires_date = NSDate(timeIntervalSinceNow: expires_in)
            
        }
        
    
    }
    //access_token的生命周期（该参数即将废弃，开发者请使用expires_in）
    var remind_in: String?
    //当前授权用户的UID。
    var uid: String?
    //用户头像地址（大图），180×180像素
    var avatar_large:String?
    //友好显示名称
    var name:String?
    
    //字典转模型
     init(dict:[String : AnyObject]){
    super.init()
    setValuesForKeysWithDictionary(dict)
    
    }
    //过滤掉没用的字段
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
//    override var description: String {
//        //打印对象格式: 类名:地址
//        //字典 数组 打印都有各式
//        //kvc将对象转换为字典
//        let keys = ["access_token","expires_in","uid"]
//        return "\(dictionaryWithValuesForKeys(keys))"
//    }
//    
    
    
   override var description: String{
    
    let keys = ["access_token","expires_in","uid","expires_date","name","avatar_large"]
        return "\(dictionaryWithValuesForKeys(keys))"
   
    }
    
    //获取路径
   static let path = (NSSearchPathForDirectoriesInDomains(
        NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.plist")
    
    //存档
    func saveAccoun(){
    
    NSKeyedArchiver.archiveRootObject(self, toFile: GYHUserAccount.path)
    
    }
    
    //获取用户名和头像
    func loadUserInfo(completion:(error:NSError?) ->()){
    
    GYHNetWorkTool.sharedTools.loadUserInfo(access_token!, uid: uid!) { (dict, error) -> () in
        
        if error != nil{
        print("网络不给力")
            completion(error: error)
            
         return
            
        }
        
        self.name = dict!["name"] as? String
        self.avatar_large = dict!["avatar_large"] as? String
        //存档
        self.saveAccoun()
        
        completion(error: nil)
        
    
        }
      
        
        
    
    }
    
    
    
    //提供一个类方法获取 GYHUserAccount
  class  func loadUserAccount() -> GYHUserAccount?{
    
//        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(GYHUserAccount.path) as ? GYHUserAccount {
//        
//        
//        return account
//        }
     //解归档
        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(GYHUserAccount.path) as? GYHUserAccount{
            
         //判断token的日期是否过期
            if account.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending{
                
              return account
                
            }
     
            
        }
        
       return nil
    
    
    }
    
    
    
    ////实现NSCoding协议的两个方法  将对象转换成为二进制数据 保存到磁盘
     func encodeWithCoder(aCoder: NSCoder){
    aCoder.encodeObject(access_token, forKey: "access_token")
    aCoder.encodeObject(remind_in, forKey: "remind_in")
    aCoder.encodeObject(uid, forKey: "uid")
    aCoder.encodeDouble(expires_in, forKey: "expires_in")
    aCoder.encodeObject(expires_date, forKey: "expires_date")
    aCoder.encodeObject(name, forKey: "name")
    aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        
    }
    
    
    //required 强制子类必须调用该方法 将磁盘中的二进制数据 -> 对象
    required init?(coder aDecoder: NSCoder){
    
    self.access_token = aDecoder.decodeObjectForKey("access_token") as? String
    self.remind_in = aDecoder.decodeObjectForKey("remind_in") as? String
    self.uid = aDecoder.decodeObjectForKey("uid") as? String

   self.expires_in = aDecoder.decodeDoubleForKey("expires_in")
        
  self.expires_date = aDecoder.decodeObjectForKey("expires_date")as? NSDate
    self.name = aDecoder.decodeObjectForKey("name")as? String
     self.avatar_large = aDecoder.decodeObjectForKey("avatar_large")as? String
        
        
        
    }
    
    
    
}
